package jdbc;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class PreparedStatementDemo {
	public static void main(String[] args) throws Exception {
		test();
	}

	private static void test() throws Exception {
		// insert into hh_stu(id,name,age,birthday)
		BufferedReader in = new BufferedReader(new InputStreamReader(
				new FileInputStream("/home/tarena/Desktop/celebrities.txt")));
		Connection con = null;
		PreparedStatement pst = null;
		try {
			con = DBUtil.open();
			pst = con.prepareStatement("insert into hh_stu " +
					"(id,name,age,birthday) values(?,?,?,?)");
			String s;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			while((s=in.readLine())!=null){
				String[] arr = s.split(",");
				pst.setInt(1, Integer.parseInt(arr[0]));
				pst.setString(2, arr[1]);
				
				if("null".equals(arr[2])){
					//基本类型插入null值
					pst.setNull(3, Types.NUMERIC);
				}else{
					pst.setInt(3, Integer.parseInt(arr[2]));
				}
				
				if("null".equals(arr[3])){
					//引用类型设置null值
					pst.setDate(4, null);
//					pst.setNull(4, Types.DATE);
				}else{
//					string->java.util.Date->毫秒->java.sql.Date
					java.util.Date d = sdf.parse(arr[3]);
					pst.setDate(4, new java.sql.Date(d.getTime()));
				}
				
				pst.executeUpdate();
				System.out.println("插入成功："+s);
			}
		} finally {
			DBUtil.close(con, pst, null);
		}
	}
}
